import { BaseContext } from "koa";
import { getRepository, Repository, Not, Equal } from "typeorm";
import { loginUtil } from "../../utils/login";
import { validate, ValidationError } from "class-validator";
import { User } from "../entity/user";
import { ip } from "../../utils/ip";
import { config } from "../../config/config";

export default class UserController {
    public static async getUsers(ctx: BaseContext) {
        try {

            const userRepository: Repository<User> = getRepository(
                User
            );
            const users: User[] = await userRepository.find({
                relations: ["role","memoLists"]
            });
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                users,
            })
        }catch(error) {
            ctx.status = 500;
            ctx.app.emit('error', {
                code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                message: ctx.ERROR.ERRORMSG_SYSTEMERROR
            }, ctx);
        }
    }

    public static async getUser(ctx: BaseContext) {

        const userRepository: Repository<User> = getRepository(
            User
        );
        console.log(`id=${ctx.query.id}`);
        const user: User = await userRepository.findOne(+ctx.query.id || 0,{
            relations: ["role","memoLists"]
        });
        if (user) {
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                id: user.id,
                name: user.name,
                email: user.email,
                phone: user.phone,
                avater: user.avater,
                roleId: user.role.id,
                roleName: user.role.name,
                roleValue: user.role.value,
                memoLists: user.memoLists,
            });
        } else {
            ctx.status = 400;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,`查找的用户id=${ctx.query.id}的用户不存在`);
        }
    }

    public static async createUser(ctx: BaseContext) {

        const userRepository: Repository<User> = getRepository(
            User
        );
        const userToBeSaved: User = new User();
        userToBeSaved.name = ctx.request.body.name;
        userToBeSaved.email = ctx.request.body.email;
        userToBeSaved.password = ctx.request.body.password;
        userToBeSaved.phone = ctx.request.body.phone;
        userToBeSaved.role = ctx.request.body.role;
        userToBeSaved.avater = ctx.request.body.avater ? ctx.request.body.avater : `http://${ip()}:${config.port}/upload/images/man.png`;
        const errors: ValidationError[] = await validate(userToBeSaved);
        console.log(`errors=${errors}`);
        if (errors.length > 0) {
            ctx.status = 400;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,errors.toString());//类似这些错误不能算系统错误，所以不适用emit error交由最外层统一处理，而是自己处理返回内容
        } else if (userToBeSaved.email && await userRepository.findOne({ email: userToBeSaved.email })) {
            ctx.status = 400;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,`邮箱：${ctx.request.body.email}已被占用`);
        } else if (userToBeSaved.phone && await userRepository.findOne({ phone: userToBeSaved.phone })) {
            ctx.status = 400;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,`手机号码：${ctx.request.body.phone}已被占用`);
        } else {
            await userRepository.save(userToBeSaved);
            await loginUtil(ctx,ctx.request.body.name,ctx.request.body.password);
        }
    }

    public static async updateUser(ctx: BaseContext) {

        if(!ctx.request.body.id) {
            ctx.status = 400;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,'必须传递需要更新的用户id');
            return false;
        }

        const userRepository: Repository<User> = getRepository(
            User
        );
        const userToBeUpdated: User = new User();
        userToBeUpdated.id = +ctx.request.body.id;
        ctx.request.body.name ? userToBeUpdated.name = ctx.request.body.name : null;
        ctx.request.body.email ? userToBeUpdated.email = ctx.request.body.email : null;
        ctx.request.body.password ? userToBeUpdated.password = ctx.request.body.password : null;
        ctx.request.body.phone ? userToBeUpdated.phone = ctx.request.body.phone : null;
        ctx.request.body.role ? userToBeUpdated.role = ctx.request.body.role : null;

        if (!(await userRepository.findOne(userToBeUpdated.id))) {
            ctx.status = 400;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,`更新的用户id=${ctx.params.id}的用户不存在`);
        } else if (
            userToBeUpdated.email && await userRepository.findOne({
                id: Not(Equal(userToBeUpdated.id)),
                email: userToBeUpdated.email
            })
        ) {
            ctx.status = 400;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,`邮箱：${ctx.request.body.email}已被占用`);
        } else if (
            userToBeUpdated.phone && await userRepository.findOne({
                id: Not(Equal(userToBeUpdated.id)),
                phone: userToBeUpdated.phone
            })
        ) {
            ctx.status = 400;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,`手机号码：${ctx.request.body.phone}已被占用`);
        } else {
            await userRepository.update(userToBeUpdated.id,userToBeUpdated);
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS);
        }
    }

    public static async deleteUser(ctx: BaseContext) {

        const id: number = +ctx.body.id;
        if(!id){
            ctx.status = 400;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,'必须提供用户id');
            return false;
        }
        const userRepository = getRepository(User);
        const userToRemove: User = await userRepository.findOne(id);
        if (!userToRemove) {
            ctx.status = 400;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,`删除的用户id=${ctx.params.id}的用户不存在`);
        } else if (+ctx.state.user.id !== userToRemove.id) {
            ctx.status = 403;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SYSTEMERROR,"用户只能自己删除")
        } else {
            await userRepository.remove(userToRemove);
            ctx.status = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS);
        }
    }
}
